<template>
  <div class="app-container">

    <div class="user-list-container">

      <div class="menu el-col-14">
        <el-button type="default" @click="addUser">添加</el-button>
      </div>
      <div class="search el-col-10">
        <el-input placeholder="搜索关键字" v-model="params.search" @keyup.enter.native="searchClick" class="input-with-select">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>

      <el-table :data="userList" v-loading="isLoading"  element-loading-text="拼命加载中" border style="width: 100%">
        <el-table-column sortable fixed="left" align="center" width="110" prop="username" label="用户名"></el-table-column>
        <el-table-column sortable align="center" min-width="90" prop="name" label="姓名"></el-table-column>
        <el-table-column sortable align="center" min-width="110" prop="phone" label="电话"></el-table-column>
        <el-table-column sortable align="center" min-width="180" prop="email" label="邮箱"></el-table-column>
        <el-table-column sortable align="center" width="90" prop="role" label="角色"
                         :filters="roles" :filter-method="filterTag" filter-placement="bottom-end">
          <template slot-scope="scope">
            <span v-for="role in roles">
              <span v-show="scope.row.role===role.value">
                <el-tag :type="role.color"
                        disable-transitions>{{ role.text }}</el-tag>
                </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column sortable align="center" width="110" prop="is_active" label="允许登陆">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_active"
              @change="allowLogin(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column sortable align="center" width="160" prop="last_login" label="最后登陆"></el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="160">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="editUserClick(scope.row)">编辑</el-button>
            <el-button size="small" type="text" @click="deleteUserClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pageination" v-show="total>5">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[5, 10, 15, 20]"
          :current-page.sync="params.page"
          :page-size="params.page_size"
          :total="total">
        </el-pagination>
      </div>

      <!-- 增加用户 -->
      <el-dialog title="增加用户" :visible.sync="addUserFormVisible" width="40%">
        <el-form ref="addUserForm" :model="userItem" label-width="70px" :rules="userRule">
          <el-form-item label="登陆名" prop="username">
            <el-input v-model="userItem.username" placeholder="请输入登陆名"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userItem.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userItem.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select class="select" v-model="userItem.role" placeholder="请选择角色">
              <el-option v-for="role in roles"
                         :label="role.text" :value="role.value" :key="role.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="属组" prop="group">
            <el-select v-model="userItem.groups" multiple placeholder="请选择用户组" style="width:100%">
              <el-option
                v-for="(item, index) in groupsList"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userItem.password" type="password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userItem.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="登陆" prop="is_active">
            <el-radio-group v-model="userItem.is_active">
              <el-radio :label="false">不允许</el-radio>
              <el-radio :label="true">允许</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeAddUserForm">取 消</el-button>
          <el-button size="small" type="primary" :loading="isLoading" @click="submitAddClick">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 编辑框 -->
      <el-dialog title="修改用户" :visible.sync="changeUserFormVisible" width="40%">
        <el-form ref="changeUserForm" :model="userItem" label-width="70px" :rules="userRule">
          <el-form-item label="用户名">
            <el-input v-model="userItem.username" placeholder="请输入登陆名" disabled></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userItem.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userItem.email" placeholder="请输入邮箱" disbaled></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select class="select" v-model="userItem.role" placeholder="请选择角色">
              <el-option v-for="role in roles"
                         :label="role.text" :value="role.value" :key="role.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="属组" prop="role">
            <el-select v-model="userItem.groups" multiple placeholder="请选择用户组" style="width:100%">
              <el-option
                v-for="(item, index) in groupsList"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="密码" prop="ch_password">
            <el-input v-model="userItem.password" type="password" placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userItem.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="登陆" prop="is_active">
            <el-radio-group v-model="userItem.is_active">
              <el-radio :label="false">不允许</el-radio>
              <el-radio :label="true">允许</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeEditUserForm">取消</el-button>
          <el-button size="small" type="primary" :loading="isLoading" @click="submitChangeUserClick">确定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
  import { getUserList, updateUser, getGroupList, createUser, deleteUser } from '@/api/users'

  export default {
    name: 'users',
    data() {
      const checkYNMobile = (rule, value, callback) => { // 校验手机号长度
        if (value) {
          if (/^\d+$/.test(value)) {
            if (value.length === 11) {
              callback()
            } else {
              callback(new Error('请确保这个字段至少包含 11 个数字'))
            }
          } else {
            callback(new Error('请确保这个字段是数字'))
          }
        } else {
          callback()
        }
      }
      const validatePass = (rule, value, callback) => { // 校验密码长度
        if (!value || value.length < 8) {
          callback(new Error('密码不能小于8位'))
        } else {
          callback()
        }
      }
      const validateChangePass = (rule, value, callback) => { // 校验密码长度
        if (value) {
          if (!value || value.length < 8) {
            callback(new Error('密码不能小于8位'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      const validateEmail = (rule, value, callback) => {
        const regEmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
        if (!regEmail.test(value)) {
          callback(new Error('请填写正确的邮箱，如: abc@126.com '))
        } else {
          callback()
        }
      }
      return {
        isLoading: false,
        addUserFormVisible: false,
        chooseGroupVisible: false,
        changeUserFormVisible: false,
        userList: [],
        userItem: {
          role: 'ordinary',
          groups: [],
          is_active: false
        },
        total: 0,
        params: {
          page: 1,
          page_size: 10,
          search: '' // 综合搜索字段
        },
        userRule: { // 校验规则
          username: [
            { required: true, message: '请输入登陆名', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          role: [
            { required: true, message: '请分配角色', trigger: 'blur' }
          ],
          password: [
            { required: true, trigger: 'blur', validator: validatePass }
          ],
          ch_password: [
            { required: false, trigger: 'blur', validator: validateChangePass }
          ],
          phone: [
            { required: false, validator: checkYNMobile, trigger: 'blur' }
          ],
          email: [
            { required: true, validator: validateEmail, trigger: 'blur' }
          ]
        },
        chooseRole: {},
        groupsList: [], // 全部组列表
        roles: [
          { value: 'supremo', text: '超级', color: 'danger' },
          { value: 'manager', text: '管理', color: 'warning' },
          { value: 'developer', text: '开发', color: 'primary' },
          { value: 'ordinary', text: '普通', color: 'success' }
        ]
      }
    },
    created() {
      this.fetchData() // 获取用户
      getGroupList({ page_size: 0 }).then( // 获取用户组
        res => {
          this.groupsList = res
        }).catch(() => {
        this.$message.error('获取用户组列表失败')
      })
    },
    methods: {
      filterTag(value, row) {
        return row.role === value
      },
      fetchData() {
        this.isLoading = true
        getUserList(this.params).then(res => {
          this.userList = res.results
          this.total = res.count
          this.isLoading = false
        }).catch(() => {
          this.isLoading = false
          this.$message.error('获取数据失败')
        })
      },
      // 改变页码和页面大小时获取对应的数据
      handleCurrentChange(val) {
        this.params.page = val
        this.fetchData()
      },
      handleSizeChange(val) {
        this.params.page_size = val
        this.fetchData()
      },
      searchClick() {
        this.params.page = 1
        this.fetchData()
      },
      addUser() {
        this.addUserFormVisible = true
      },
      editUserClick(user) {
        this.userItem = { ...user }
        this.changeUserFormVisible = true
      },
      submitChangeUserClick() {
        this.$refs['changeUserForm'].validate(
          (valid) => {
            if (!valid) {
              return
            }
            const { id, ...data } = this.userItem
            updateUser(id, data).then(
              () => {
                this.closeEditUserForm()
                this.fetchData()
                this.$message.success('操作成功')
              }).catch(() => {
              this.closeEditUserForm()
              this.$message.error('操作失败')
            })
          })
      },
      closeEditUserForm() {
        this.changeUserFormVisible = false
        this.userItem = { role: 'ordinary', groups: [], is_active: false }
        this.$refs['changeUserForm'].resetFields()
        this.$message.info('操作取消')
      },
      allowLogin(user) {
        updateUser(user.id, { is_active: user.is_active }).then(
          () => {
            this.fetchData()
            this.$message.success('操作成功')
          }).catch(() => {
          this.$message.success('操作失败')
        })
      },
      closeAddUserForm() {
        this.addUserFormVisible = false
        this.userItem = { role: 'ordinary', groups: [], is_active: false }
        this.$refs['addUserForm'].resetFields()
        this.$message.info('操作取消')
      },
      submitAddClick() {
        this.$refs['addUserForm'].validate(
          (valid) => {
            if (!valid) {
              return
            }
            this.isLoading = true
            createUser({ ...this.userItem }).then(
              () => {
                this.isLoading = false
                this.addUserFormVisible = false
                this.closeAddUserForm()
                this.fetchData()
                this.$message.success('操作成功')
              }).catch(() => {
              this.isLoading = false
              this.addUserFormVisible = false
              this.closeAddUserForm()
              this.$message.error('操作失败')
            })
          })
      },
      deleteUserClick(user) {
        this.$confirm(`确认删除用户 ${user.name} 的连接信息吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(
          () => {
            deleteUser(user.id).then(
              () => {
                this.fetchData()
                this.$message.success('删除用户成功')
              }).catch(
              () => {
                this.$message.error('删除用户失败')
              })
          }).catch(
          () => {
            this.$message.info('已取消删除')
          })
      }
    }
  }
</script>

<style lang="scss" scoped>
.user-list-container {
  .pageination {
    text-align: center;
    margin-top: 15px;
  }
  .search {
    margin-bottom: 10px;
  }
  .select {
    width: 100%;
  }
}
</style>
